package main

import (
	"encoding/hex"
	"fmt"
	"github.com/spf13/cobra"
	sm509 "github.com/tjfoc/gmsm/x509"
)

func TestSm2PrivateKey(privateKeyStr string) error {

	privateKeyBytes, err := hex.DecodeString(privateKeyStr)
	if err != nil {
		return err
	}
	fmt.Printf("Private key hex: %x\n", privateKeyBytes)

	privKey, err := sm509.ReadPrivateKeyFromHex(privateKeyStr)
	if err != nil {
		return err
	}
	fmt.Printf("Private key: %064x, pub (%064x, %064x)\n", privKey.D, privKey.X, privKey.Y)

	return nil
}

var privKeyCmd = &cobra.Command{
	Use:   "privKey",
	Short: "私钥测试命令",
	Long: `例如：gmTool.exe privKey --private [私钥十六进制数据，长度为64]
	`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("generate key called")

		privateKeyStr, err := cmd.Flags().GetString("private")
		if err != nil {
			fmt.Printf("Error: %v\n", err.Error())
			return
		}
		if len(privateKeyStr) == 0 {
			fmt.Printf("Error: 私钥数据不能为空\n")
			return
		}

		keyType, _ := cmd.Flags().GetString("keyType")
		if keyType == "sm2" {
			err = TestSm2PrivateKey(privateKeyStr)
			if err != nil {
				fmt.Printf("Error: %v\n", err.Error())
				return
			}
		} else {
			fmt.Printf("Not supported keyType value: %s\n", keyType)
		}

	},
}

func init() {
	rootCmd.AddCommand(privKeyCmd)

	// Here you will define your flags and configuration settings.
	privKeyCmd.Flags().StringP("private", "p", "", "私钥数据")
	privKeyCmd.Flags().StringP("keyType", "t", "", "私钥类型， sm2或rsa")
}
